#include <QAndroidJniObject>
#include <QtAndroid>

#include "AndroidPicker.h"


namespace TC
{

    AndroidPicker::AndroidPicker(QString contentType, QObject *parent /*= nullptr*/)
        : QObject(parent), contentType(contentType)
    {

    }

    QUrl AndroidPicker::fileUrl()
    {
        return _fileUrl;
    }

    void AndroidPicker::open()
    {
        QAndroidJniObject ACTION_PICK = QAndroidJniObject::fromString("android.intent.action.GET_CONTENT");
        QAndroidJniObject intent("android/content/Intent");
        if (ACTION_PICK.isValid() && intent.isValid())
        {
            intent.callObjectMethod("setAction", "(Ljava/lang/String;)Landroid/content/Intent;", ACTION_PICK.object<jstring>());
            intent.callObjectMethod("setType", "(Ljava/lang/String;)Landroid/content/Intent;", QAndroidJniObject::fromString(contentType).object<jstring>());
            QtAndroid::startActivity(intent.object<jobject>(), 101, this);
        }
        else
        {
            error();
        }
    }

    void AndroidPicker::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject & data)
    {
        jint RESULT_OK = QAndroidJniObject::getStaticField<jint>("android/app/Activity", "RESULT_OK");
        if (receiverRequestCode == 101 && resultCode == RESULT_OK) {
            _fileUrl = QUrl::fromLocalFile(data.callObjectMethod("getData", "()Landroid/net/Uri;").callObjectMethod("getPath", "()Ljava/lang/String;").toString());
            fileUrlChanged();
            accepted();
        }
        else
        {
            rejected();
        }
    }

}
